﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LabelPrint.Util;

namespace LabelPrint.Models
{
    public class Coils
    {
        public int CoilID { get; set; }
        public string CoilName { get; set; }
        public decimal CoilFormat { get; set; }
        public decimal NetoWeight { get; set; }
        public decimal TaraWeight { get; set; }
        public decimal AccurateNetoWeight { get; set; }
        public decimal AccurateTaraWeight { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public bool IsFaulty { get; set; }
        public string FaultDescription { get; set; }
        public DateTime NetoWeightUpdated { get; set; }
        public bool Collected { get; set; }
        public decimal AccurateGrossWeight { get; set; }
        public DateTime GrossWeightUpdated { get; set; }

        public static IEnumerable<Coils> QueryLatestCoils(string coilName)
        {
            if (!string.IsNullOrWhiteSpace(coilName) && coilName.Length >= 10 && !coilName.Contains("_"))
            {
                coilName = coilName.Substring(0, 6) + "_" + coilName.Substring(6);
            }
            const string sql =
@"IF ( @coilName IS NOT NULL )
    BEGIN
        SELECT  *
        FROM    dbo.Coils
        WHERE   CoilName > @coilName
        ORDER BY CoilID DESC
    END
ELSE
    BEGIN 
        SELECT TOP 1
                *
        FROM    coils
        ORDER BY CoilID DESC
    END
";
            return DbUtil.Query<Coils>(sql, new { coilName = coilName });
        }

        public static int UpdateCoilsWeight(string coilName, decimal accurateGrossWeight, decimal accurateTaraWeight,
            decimal accurateNetoWeight)
        {
            if (!string.IsNullOrWhiteSpace(coilName) && coilName.Length >= 10)
            {
                coilName = coilName.Substring(0, 6) + "_" + coilName.Substring(6);
            }
            const string sql = @"
update Coils 
set 
    AccurateGrossWeight=@AccurateGrossWeight,
    AccurateTaraWeight=@AccurateTaraWeight,
    AccurateNetoWeight=@AccurateNetoWeight
where
    CoilName = @CoilName
";
            return DbUtil.Execute(sql,
                new
                {
                    AccurateGrossWeight = accurateGrossWeight,
                    AccurateTaraWeight = accurateTaraWeight,
                    AccurateNetoWeight = accurateNetoWeight,
                    CoilName = coilName
                });
        }

        private static string _file = "coil.info";
        private static string _coilName = null;
        public static string GetLastCoilName()
        {
            return _coilName;
        }

        public static void WriteCoilName(string coilName)
        {
            _coilName = coilName;
        }
    }
}
